﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using Operation;
using pinduoduo.Util;
using Sunny.UI;
using Tk.Soc.Share.Common.Helpers;

namespace pinduoduo.From
{
    public partial class AutoPayFrom : UIForm
    {

        private ChromiumWebBrowser AccountChromeBrowser;

        private RequestContext AccountContext;

        public string ZhiFuPassword { get; set; }

        private string payUrl;
        private string password;
        private bool isDriver;

        public AutoPayFrom(string payUrl, string password,bool isDriver =false)
        {
            this.payUrl = payUrl;
            this.password = password;
            this.isDriver = isDriver;
            InitializeComponent();
            InitializeAccountChromium();

            var image = AlipayHelper.CreateQRCode(payUrl, 330);
            this.pictureBox1.Image = image;

        }

        private void AutoPayFrom_Load(object sender, EventArgs e)
        {

        }


        public async void AutoPay(string url, string password, bool isClose = false, int timeout = 5000)
        {
            ChromeDriverService service = ChromeDriverService.CreateDefaultService();
            service.LogPath = AppDomain.CurrentDomain.BaseDirectory + "drive";
            IWebDriver driver = await GetDriver(service);

            if (driver == null)
            {
                ShowErrorNotifier("自动支付驱动异常，请重试或重启软件!");
                return;
            }
            try
            {
                //driver.Navigate().GoToUrl(url);
                var zhifuButton = By.XPath("//*[@id=\"cashierPreConfirm\"]/div[2]/button");
                driver.FindElement(zhifuButton).Click();
                var payInput = By.XPath("//*[@id=\"pwd_unencrypt\"]");

                driver.SwitchTo().DefaultContent();
                driver.FindElement(payInput).SendKeys(password);
                Thread.Sleep(2000);

                var buttonsEl = driver.FindElements(By.TagName("button"));
                foreach (var item in buttonsEl)
                {
                    if (item.Text == "确定") {
                        item.Click();
                        await Task.Delay(300);
                        break;
                    }
                }
                string nextUrl = driver.Url;
                if (nextUrl.Contains("https://mclient.alipay.com/h5/cashierPay.htm?awid="))
                {
                    int delay = 0;
                    while (true)
                    {
                        if (driver.PageSource.Contains("短信校验码") && driver.PageSource.Contains("收到的短信校验码"))
                        {
                            ShowErrorNotifier("任务失败");
                            break;
                        }
                        var successEl = driver.FindElement(By.ClassName("J-success"));
                   

                        if (successEl != null && successEl.Displayed)
                        {
                            ShowSuccessNotifier("任务成功");

                            if (isClose)
                            {
                                this.DialogResult = DialogResult.OK;
                                this.Close();
                            }

                            return;
                        }
                        await Task.Delay(500);
                        delay += 500;
                        if (delay > timeout * 1000)
                        {
                            break;
                        }
                    }

                    ShowErrorNotifier("任务失败");
                }
                else
                {
                    ShowErrorNotifier("任务失败");
                }
            }
            catch (Exception e)
            {
                LogHelper.Logger.Error("自动支付异常：", e);
                ShowErrorNotifier("任务失败");
            }
            finally
            {
                await Task.Run(() =>
                {
                    driver?.Close();
                    driver?.Quit();
                    driver?.Dispose();
                });

            }
        }

        public static async Task<IWebDriver> GetDriver(ChromeDriverService chromeDriverService)
        {
            IWebDriver driver = null;
            await Task.Run(() =>
            {
                try
                {
                    ChromeOptions options = new ChromeOptions();
                    options.DebuggerAddress = "127.0.0.1:22222";
                    options.AddArgument("no-sandbox");
                    chromeDriverService.HideCommandPromptWindow = true;
                    driver = new ChromeDriver(chromeDriverService, options, TimeSpan.FromSeconds(10));
                }
                catch (Exception e)
                {
                    if (driver != null)
                    {
                        driver?.Close();
                        driver?.Quit();
                        driver?.Dispose();
                    }
                    driver = null;
                }
            });
            return driver;
        }


        public async void AutoPay(bool isClose = true, int timeout = 15)
        {

            await Task.Delay(1000);
            string js = "getElementsByText('确认付款','button')[0]";
            int delay = 0;

            while (true)
            {
                try
                {
                    string temp = Browser.JS_CEFBrowser("getElementsByText('确认付款','button')[0].offsetParent !==null", AccountChromeBrowser);

                    if (!string.IsNullOrEmpty(temp) && temp == "True")
                    {
                        delay = 0;
                        Browser.MouseLeftByHtmlElement("getElementsByText('确认付款','button')[0]", AccountChromeBrowser, false);
                        await Task.Delay(1000);
                        Browser.MouseLeftByHtmlElement("document.getElementById('pwd_unencrypt')", AccountChromeBrowser, true);
                        Browser.Delay(300);

                        temp = Browser.JS_CEFBrowser("getElementsByText('确定','button')[0].offsetParent !==null", AccountChromeBrowser);
                        if (!string.IsNullOrEmpty(temp) && temp == "True")
                        {
                            SendKeys.SendWait(password);
                            await Task.Delay(200);
                            Browser.MouseLeftByHtmlElement("getElementsByText('确定','button')[0]", AccountChromeBrowser, false);
                        }
                        else
                        {
                            SendKeys.SendWait(password);
                            await Task.Delay(2000);
                        }

                        delay = 0;
                        while (true)
                        {
                            string PageSource = await AccountChromeBrowser.GetBrowser().MainFrame.GetSourceAsync();
                            if (PageSource.Contains("短信校验码") && PageSource.Contains("收到的短信校验码"))
                            {
                                ShowErrorNotifier("任务失败");
                                break;
                            }

                            string script = @"(function() { return  $('.J-success').css('display');})()";

                            JavascriptResponse javascriptResponse = await AccountChromeBrowser.EvaluateScriptAsync(script);
                            if (javascriptResponse.Result != null && !string.IsNullOrWhiteSpace(javascriptResponse.Result.ToString()) && javascriptResponse.Result.ToString() == "block")
                            {
                                ShowSuccessNotifier("任务成功");
                                if (isClose)
                                {
                                    this.DialogResult = DialogResult.OK;
                                    this.Close();
                                }

                                return;
                            }


                            await Task.Delay(500);
                            delay += 500;
                            if (delay > timeout * 1000)
                            {
                                break;
                            }
                        }

                        ShowErrorNotifier("任务失败");
                        break;
                    }

                    await Task.Delay(500);
                    delay += 500;
                    if (delay > timeout * 1000)
                    {
                        ShowErrorNotifier("任务超时");
                        break;
                    }
                }
                catch (Exception)
                {

                }

            }
        }


        //初始化浏览器并启动
        public void InitializeAccountChromium()
        {

            AccountContext = new RequestContext(new RequestContextSettings()
            {
                CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\global1\\",
                PersistSessionCookies = true,
                PersistUserPreferences = true
            });

            AccountChromeBrowser = new ChromiumWebBrowser(this.payUrl, AccountContext);
            BrowserSettings browserSettings = new BrowserSettings();
            browserSettings.ApplicationCache = CefState.Enabled;

            AccountChromeBrowser.BrowserSettings = browserSettings;

#if DEBUG
            AccountChromeBrowser.KeyboardHandler = new CEFKeyBoardHander();
#endif
            this.panel1.Controls.Add(AccountChromeBrowser);


            AccountChromeBrowser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;

            AccountChromeBrowser.Dock = DockStyle.Fill;
        }

        private void OnIsBrowserInitializedChanged(object sender, EventArgs args)
        {
            SetCookie(CefUtils.GetAccountContext());
        }

        private string pddurl = "http://yangkeduo.com/";

        public async void SetCookie(RequestContext AccountContext)
        {
            List<CefSharp.Cookie> cookies = await AccountContext.GetCookieManager(null).VisitUrlCookiesAsync(pddurl, true);

            foreach (var item in cookies)
            {
                await AccountChromeBrowser.GetCookieManager().SetCookieAsync(pddurl, item);
            }
        }

        private void AutoPayFrom_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void AutoPayFrom_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void AutoPayFrom_Shown(object sender, EventArgs e)
        {
            if (this.isDriver) 
            {
                return;
            }
            try
            {
                AutoPay();
            }
            catch (Exception e1)
            {

            }

        }

        private async void button1_Click(object sender, EventArgs e)
        {
            ////mclient.alipay.com
            //if (ShowAskDialog("您确定切换支付宝账户吗", "提示框"))
            //{
            //    await AccountContext.GetCookieManager(null).DeleteCookiesAsync("https://mclient.alipay.com");
            //    AccountChromeBrowser.Load(this.payUrl);
            //}
            string script = @"(function() { return  document.getElementsByClassName('J-success')[0].offsetParent;})()";
            string temp1 = Browser.JS_CEFBrowser("getElementsByText('支付成功','h4')[0].offsetParent !==null", AccountChromeBrowser);
            JavascriptResponse javascriptResponse = await AccountChromeBrowser.EvaluateScriptAsync(script);
            //if (javascriptResponse.Result != null && !string.IsNullOrWhiteSpace(javascriptResponse.Result.ToString()))
            if (!string.IsNullOrEmpty(temp1) && temp1 == "True")
            {
                ShowSuccessNotifier("任务成功");

                //if (isClose)
                //{
                //    this.DialogResult = DialogResult.OK;
                //    this.Close();
                //}

                return;
            }
        }

        private async void uiButton4_Click(object sender, EventArgs e)
        {
            await AccountChromeBrowser.GetCookieManager(null).DeleteCookiesAsync();
            await AccountChromeBrowser.GetCookieManager(null).FlushStoreAsync();
        }
    }
}
